package cn.fzkj.controller;

import cn.fzkj.domain.SysJob;
import cn.fzkj.dxception.TaskException;
import cn.fzkj.service.JobService;
import cn.fzkj.util.QuartzDisallowConcurrentExecution;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/job")
public class IndexController {


    @Autowired
    private JobService jobService;

    @GetMapping
    public List<SysJob> get(){
        return jobService.selectJobList(new SysJob());
    }

    @PostMapping
    public int post(@RequestBody SysJob job) throws SchedulerException, TaskException {
        return jobService.insertJob(job);
    }

    @PutMapping("/resume")
    public int resume(@RequestBody SysJob job) throws SchedulerException {
        return jobService.resumeJob(job);
    }

    @PutMapping("/pause")
    public int pause(@RequestBody SysJob job) throws SchedulerException {
        return jobService.pauseJob(job);
    }

    @DeleteMapping()
    public int delete(@RequestBody SysJob job) throws SchedulerException {
        return jobService.deleteJob(job);
    }

    @Autowired
    Scheduler scheduler;
    @GetMapping("/new")
    public void new1() throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(QuartzDisallowConcurrentExecution.class)
                /**给当前JobDetail添加参数，K V形式*/
                .usingJobData("name","zy")
                /**给当前JobDetail添加参数，K V形式，链式调用，可以传入多个参数，在Job实现类中，可以通过jobExecutionContext.getJobDetail().getJobDataMap().get("age")获取值*/
//                .usingJobData("age",23)
                /**添加认证信息，有3种重写的方法，我这里是其中一种，可以查看源码看其余2种*/
                .withIdentity("我是name","我是group")
                .build();
        SysJob job = new SysJob();
        job.setJobId(321L);
        job.setJobName("计划生成任务job");
        job.setJobGroup("DEFAULT");
        job.setCronExpression("0/10 * * * * ?");
        job.setInvokeTarget("planTask.generateTask(1)");
        job.setConcurrent("1");
        job.setStatus("0");

        jobDetail.getJobDataMap().put("TASK_PROPERTIES", job);

        CronTrigger  trigger = TriggerBuilder.newTrigger()
                /**给当前JobDetail添加参数，K V形式，链式调用，可以传入多个参数，在Job实现类中，可以通过jobExecutionContext.getTrigger().getJobDataMap().get("orderNo")获取值*/
                .usingJobData("orderNo", "123456")
                /**添加认证信息，有3种重写的方法，我这里是其中一种，可以查看源码看其余2种*/
                .withIdentity("我是name","我是group")
                /**立即生效*/
//      .startNow()
                /**开始执行时间*/
//                .startAt(start)
                /**结束执行时间,不写永久执行*/
//                .endAt(start)
                /**添加执行规则，SimpleTrigger、CronTrigger的区别主要就在这里,我这里是demo，写了个每2分钟执行一次*/
                .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
                .build();//执

        scheduler.scheduleJob(jobDetail, trigger);

    }

}
